<?php

namespace App\Repository\Service;

use App\Api\Sms\SmsClient;
use App\Jobs\TaskUploadExcel;
use App\Models\Admin\AdminUsers;
use App\Models\Orders\OrdersModel;
use App\Models\Orders\OrdersUserModel;
use App\Models\Service\ServiceCallModel;
use App\Models\Service\ServiceCallTaskModel;
use App\Models\Sms\SmsSendLogModel;
use App\Models\Sms\SmstmpModel;
use App\Repository\BaseRepository;

class ServiceCallTaskRepository extends BaseRepository
{
    public $model;
    public $log;

    public function __construct()
    {
        $this->model = new ServiceCallTaskModel();
//    $this->log = new Logger('anchor');
//    $this->log->pushHandler(
//      (new RotatingFileHandler(storage_path('/logs/anchor.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
//    );
        parent::__construct();
    }


    public function index($params, $page = 1, $limit = 10)
    {
        $where = [];
        if (isset($params['title'])) {
            $where['where']['title'] = $params['title'];
        }
        if (isset($params['dateRange'])) {
            $params['dateRange'] = [date('Y-m-d', strtotime($params['dateRange'][0])), date('Y-m-d', strtotime($params['dateRange'][1])) . ' 23:59:59'];
            $where['between']['created_at'] = $params['dateRange'];
        }
        $count = 0;
        if ($page <= 1) {
            $count = $this->model->searchWhere($where)->count('id');
        }
        $ModelUser = new AdminUsers();
        $rows = [];
        foreach ($this->model->from($this->model->getTable(), 'a')
                     ->leftJoin($ModelUser->getTable() . ' AS b', 'a.service_user_id', '=', 'b.id')
                     ->searchWhere($where)
                     ->select(['a.*', 'b.nick_name'])
                     ->page($page, $limit)
                     ->orderByDesc('a.id')->cursor() as $row) {
            $cond = json_decode($row['orders_condition'], true);
            $row['flag_ok_rate'] = 0;
            if ($row['overs'] > 0) {
                $row['flag_ok_rate'] = round($row['flag_ok'] / $row['overs'] * 100, 1);
            }
            if ($row['type'] == 1) {
                $row['file_src'] = $cond['file_src'];
                $row['orders_condition'] = null;
            } else {
                $row['orders_condition'] = $cond;
            }
            $rows[] = $row;
        }
        return $this->returnMsg(200, '查询成功', $rows, $count);
    }

    //列表
    public function hall($params, $page = 1, $limit = 10)
    {
        $where = [];
        $where['eq']['status'] = $params['status'] ?? 0;
        //        只显示客服自己的或上级是指定的客服的列表
        if (intval($params['user']['role_id']) !== 1) {
            $where['eq']['service_user_id'] = $params['user']['id'] ?? 0;
            if ($params['user']['supervisor_id'] > 0) {
                $where['or']['service_user_id'] = $params['user']['supervisor_id'];
            }
        }
        if (isset($params['dateRange'])) {
            $params['dateRange'] = [date('Y-m-d', strtotime($params['dateRange'][0])), date('Y-m-d', strtotime($params['dateRange'][1])) . ' 23:59:59'];
            $where['between']['created_at'] = $params['dateRange'];
        }
        if (isset($params['title'])) {
            $where['eq']['title'] = $params['title'];
        }
        $count = 0;
        if ($page <= 1) {
            $count = $this->model->searchWhere($where)->count('id');
        }
        $rows = [];
        foreach ($this->model->searchWhere($where)->page($page, $limit)->orderByDesc('weight')->cursor() as $row) {
            $row['flag_ok_rate'] = 0;
            if ($row['overs'] > 0) {
                $row['flag_ok_rate'] = round($row['flag_ok'] / $row['overs'] * 100, 1);
            }
            $rows[] = $row;
        }
        return $this->returnMsg(200, '查询成功', $rows, $count);
    }

//发送短信
    public function sendTplSms($params)
    {
        $ordersId = $params['ordersId'];
        $smsTplId = $params['smsTplId'];
        $ModelOrders = new OrdersModel();
        $ModelOrdersUser = new OrdersUserModel();
        $orders = $ModelOrders->from($ModelOrders->getTable(), 'a')
            ->leftJoin($ModelOrdersUser->getTable() . ' AS b', 'a.ordersno', '=', 'b.orderno')
            ->select(['a.*', 'b.*'])
            ->where(['a.id' => $ordersId])
            ->first();
        if (empty($orders)) {
            return $this->returnMsg(2, '订单数据异常');
        }
        $ModelSmsTmp = new SmstmpModel();
        $data = $ModelSmsTmp->where(['id' => $smsTplId])->first();
        if (empty($data['tpl_id'])) {
            return $this->returnMsg(2, '短信模板没找到');
        }
        if ($data['verify_status'] != 2) {
            return $this->returnMsg(2, '短信模板还没有审核成功,不能发送');
        }
        $SmsApi = new SmsClient();
        $phone = $orders['contact_phone'];
        if (empty($phone)) {
            $phone = $orders['pay_phone'];
        }
        if (empty($phone)) {
            return $this->returnMsg(2, '订单没有有效联系电话');
        }
        $res = $SmsApi->sendSmsByTpl($orders['pay_phone'], $data['tpl_id'], $data['type'], $data['content'], $orders);
//        记录发送日志
        if ($res['code'] != 200) {
            return $this->returnMsg(2, '短信发送失败');
        }
        $ModelLogs = new SmsSendLogModel();
        $field = $ModelLogs->getTableField();
//        取一些订单数据信息
        $arr = [];
        foreach ($field as $k => $v) {
            if (in_array($v, ['id', 'created_at', 'created_by', 'updated_by', 'order_num', 'remark', 'updated_at'])) {
                continue;
            }
            $arr[$v] = $orders[$v] ?? '';
        }
        $smsLog = [
            'sms_use_type' => $data['use_type'],
            'sms_id' => $res['data']['smsId'],
            'sms_tmp_name' => $data['name'],
            'sms_tmp_id' => $data['tpl_id'],
            'phone' => $phone,
            'content' => $SmsApi->parseTplContent($data['content'], $orders),
            'order_id' => $ordersId,
            'is_send' => 2,
            'status' => 2,
            'created_at' => date('Y-m-d H:i:s'),
            'created_by' => $params['user']['id']
        ];
        $ModelLogs->insert(array_merge($arr, $smsLog));
        return $this->returnMsg(200, '短信发送完成');
    }

//    指定任务的订单列表数据
    public function callTaskLogs($id, $page = 1, $limit = 10)
    {
        $where = [];
        $where['eq']['id'] = $id;
        $row = $this->model->searchWhere($where)->page($page, $limit)->first();
        $cond = json_decode($row['orders_condition'], true);
        $nos = [];
        if (isset($cond['works'])) {
            $nos = $cond['works'];
        }
        if (isset($cond['done'])) {
            $nos = array_merge($nos, array_keys($cond['done']));
        }

        $count = count($nos);
        //偏移量，当前页-1乘以每页显示条数
        $start = ($page - 1) * $limit;
        $ordersNos = array_slice($nos, $start, $limit);
        if (empty($ordersNos)) {
            return $this->returnMsg(200, '查询成功', [], 0);
        }
        $ModelOrders = new OrdersModel();
        $where = [];
        $where['in']['ordersno'] = $ordersNos;
        $fields = ['id as orders_id', 'ordersno', 'status', 'product_name', 'product_code', 'created_at'];
        $rows = [];
        foreach ($ModelOrders->searchWhere($where)->select($fields)->cursor() as $row) {
            $row['talk_time'] = 0;
            $row['has_talk'] = '待拨打';
            $row['talk_orders_status'] = -1;
            if (isset($cond['done'][$row['ordersno']])) {
                $row['has_talk'] = '已拨打';
                $row['talk_time'] = $cond['done'][$row['ordersno']]['talk_time'] ?? 0;
                $row['talk_orders_status'] = $cond['done'][$row['ordersno']]['orders_status'] ?? -1;
            }
            $rows[] = $row;
        }
        $statusList = config('card.ordersStatus');
        return $this->returnMsg(200, '查询成功', $rows, $count, $statusList);
    }

//    点拨打时先保存数据,然后打完无论是标记还是推送拨打信息都用更新方式
    public function setCallFlag($params)
    {
        $call_task_id = $params['call_task_id'] ?? 0;
        $ordersno = $params['ordersno'] ?? '';
        $type = $params['type'] ?? 0;
        $usersId = $params['user']['id'];
        $inData = [
//            'call_id' => 'kk' . md5($usersId . time() . uniqid()),
            'type' => $type,
            'phone' => $params['phone'] ?? '',
            'users_id' => $usersId,
            'nickname' => $params['user']['nick_name'] ?? '',
            'call_task_id' => $call_task_id,
            'orders_id' => $params['orders_id'] ?? 0,
            'ordersno' => $ordersno,
            'orders_status' => $params['orders_status'] ?? 0,
            'service_user_id' => $params['service_user_id'] ?? 0,
            'md5sum' => md5($params['md5str']),
            'created_at' => date('Y-m-d H:i:s'),
            'overed_at' => date('Y-m-d H:i:s'),
            'talk_time' => 0,
            'status' => 0
        ];
        $ModelServiceCall = new ServiceCallModel();
        $where = [
            'type' => $type,
            'call_task_id' => $call_task_id,
            'status' => 0,
            'service_user_id' => $inData['service_user_id'],
            'orders_id' => $inData['orders_id'],
        ];
//        非任务,是可以多个人点击拨打的,要区分当前拨打人,任务里只有一个记录
        if ($call_task_id <= 0) {
            $where = [
                'md5sum' => $inData['md5sum']
            ];
        }
        //        采用了指定任务id方式
        if (isset($params['service_call_id']) && $params['service_call_id'] > 0) {
            $where = ['id' => $params['service_call_id']];
        }
        $oldRow = $ModelServiceCall->where($where)->select(['id', 'md5sum'])->first();
        if (empty($oldRow)) {
            $ModelServiceCall->insert($inData);
        } else {
            $upData = [
                'phone' => $inData['phone'],
                'users_id' => $usersId,
                'nickname' => $inData['nickname'],
                'ordersno' => $ordersno,
                'orders_status' => $inData['orders_status'],
                'status' => $inData['status'],
                'md5sum' => $inData['md5sum'],
            ];
            $ModelServiceCall->where(['id' => $oldRow->id])->update($upData);
        }
        return $this->returnMsg(200, '外呼数据已保存');

    }

//接一个外呼订单给打电话
    public function getCallTaskOrder($id)
    {
        $data = $this->model->where(['id' => $id, 'status' => 0])->select(['speech', 'status'])->first();
        if (empty($data)) {
            return $this->returnMsg(2, '任务已完成');
        }
        $ModelServiceCall = new ServiceCallModel();
        $where = [
            'call_task_id' => $id,
            'status' => 0
        ];
        $callData = $ModelServiceCall->where($where)->select(['id', 'ordersno'])->orderBy('id', 'asc')->first();
        if (empty($callData)) {
            if ($data['status'] != 2) {
                $this->model->where(['id' => $id])->update(['status' => 2]);
            }
            return $this->returnMsg(2, '本任务已外呼完毕');
        }
//        标识任务进行中
//        $ModelServiceCall->where(['id' => $callData['id']])->update(['status' => 10]);
        $ordersNo = $callData->ordersno;
        $serviceCallId = $callData->id;

        $where = [];
        $where['eq']['ordersno'] = $ordersNo;
        $ModelOrders = new OrdersModel();
        $ModelOrdersUser = new OrdersUserModel();
        $aFields = ['a.id', 'a.created_at', 'a.ordersno', 'a.status', 'a.first_money', 'a.activat_at', 'a.sup_orderno', 'a.goods_name', 'a.goods_code', 'a.goods_id', 'a.iccid', 'a.three_msg', 'a.product_name', 'a.express_company', 'a.express_number', 'a.express_phone', 'a.express_desc', 'a.express_status', 'a.remark', 'a.service_user_id'];
        $bFields = ['b.source', 'b.orderno', 'b.contact_name', 'b.contact_phone', 'b.pay_name', 'b.pay_phone', 'b.pay_identity', 'b.post_province', 'b.post_city', 'b.post_area', 'b.post_address', 'b.tagging', 'b.sku_number', 'b.sku_area'];
        $fields = array_merge($aFields, $bFields);
        $row = $ModelOrders->from($ModelOrders->getTable(), 'a')
            ->leftJoin($ModelOrdersUser->getTable() . ' AS b', 'a.ordersno', '=', 'b.orderno')
            ->select($fields)
            ->searchWhere($where)
            ->first();
        if (empty($row)) {
            return $this->returnMsg(3, '没有外呼订单数据');
        }
        $row['speech'] = $data['speech'];
        $row['service_call_id'] = $serviceCallId;
        return $this->returnMsg(200, '已为你获取取了新的外呼订单', $row);

    }

    public function edit($postData)
    {
        return $this->returnMsg(2, '任务不能修改,可以删除新增任务');
    }

    public function add($postData)
    {
        if (empty($postData['user'])) {
            return $this->returnMsg(2, '帐号信息异常');
        }
        $loginUsersId = $postData['user']['id'];
        $loginUsersShopId = $postData['user']['shop_id'];
//        必填写字段
        $mustFields = [
            "title" => '标题必填写'
        ];
//        接受的字段
        $optionalFields = [
            'weight',
            'type',
            'status',
            'speech',
            'pid',
            'orders_condition',
        ];
        $inData = $this->getRealData($postData, array_keys($mustFields), $optionalFields, $mustFields);
        if (empty($inData) || is_string($inData)) {
            return $this->returnMsg(
                2,
                $inData
            );
        }
        $inData['users_id'] = $loginUsersId;
        $inData['created_at'] = date('Y-m-d H:i:s');
        $inData['status'] = $postData['status'] ?? 0;
        if (empty($inData['orders_condition'])) {
            return $this->returnMsg(2, '条件数据不能为空');
        }
//            根据任务条件,找出订单保存
        $ModelOrders = new OrdersModel();
        $cond = $inData['orders_condition'];
//        创建回收任务
        if ($inData['pid'] > 0) {
            return $this->createRecoveryTask($postData, $cond);
        }
        $where = [];

//            根据任务归属客服找定单
        $where['gt']['a.service_user_id'] = 0;
        if (!empty($cond['shop_id'])) {
//            指定了分销店铺
            $shop_id = $where['eq']['a.shop_id'] = $cond['shop_id'];
        } else {
//            登陆者店铺
            $shop_id = $where['eq']['a.shop_id'] = $loginUsersShopId;
        }
        if (!empty($cond['array_product_id'])) {
            if (count($cond['array_product_id']) == 1) {
                $where['eq']['a.product_id'] = $cond['array_product_id'][0];
            } else {
                $where['in']['a.product_id'] = $cond['array_product_id'];
            }
        }
        if (!empty($cond['array_orders_status'])) {
            if (count($cond['array_orders_status']) == 1) {
//                不要回收单
                if ($cond['array_orders_status'][0] != 70) {
                    $where['eq']['a.status'] = $cond['array_orders_status'][0];
                }
            } else {
//                不要回收单
                $statusArray = array_values(array_diff($cond['array_orders_status'], [70]));
                $where['in']['a.status'] = $statusArray;
            }
        } else {
            $where['neq']['a.status'] = 70;
        }
        // 在网选项
        if (!empty($cond['array_online_status'])) {
            if (count($cond['array_online_status']) == 1) {
                $where['eq']['a.is_online'] = $cond['array_online_status'][0];
            } else {
                $where['in']['a.is_online'] = $cond['array_online_status'];
            }
        }


        if (!empty($cond['array_source_status'])) {
            if (count($cond['array_source_status']) == 1) {
                $where['eq']['b.source'] = $cond['array_source_status'][0];
            } else {
                $where['in']['b.source'] = $cond['array_source_status'];
            }
        }

        if (isset($cond['activat_status'])) {
            $activatStatus = intval($cond['activat_status']);
            if ($activatStatus == 1) {
//                已激活订单
                $where['eq']['a.activat_status'] = 1;
            } else {
                $where['eq']['a.activat_status'] = 0;
            }
        }
        if (isset($cond['first_status'])) {
            $activatStatus = intval($cond['first_status']);
            if ($activatStatus == 1) {
//                已充值订单
                $where['eq']['a.first_status'] = 1;
            } else {
                $where['eq']['a.first_status'] = 0;
            }
        }
        if (isset($cond['first_money_index'])) {
            $firstMoneyList = config('card.firstMoneyList');
            $firstMoneyItemKey = intval($cond['first_money_index']);
            $firstMoneyItem = $firstMoneyList[$firstMoneyItemKey];
            if ($firstMoneyItem['symbol'] != 'between') {
                $where[$firstMoneyItem['symbol']]['a.first_money'] = $firstMoneyItem['value'];
            } else {
                $where['between']['a.first_money'] = $firstMoneyItem['value'];
            }
        }
        if (isset($cond['created_at']) && is_array($cond['created_at'])) {
            $cond['created_at'] = [date('Y-m-d', strtotime($cond['created_at'][0])), date('Y-m-d', strtotime($cond['created_at'][1])) . ' 23:59:59'];
            $where['between']['a.created_at'] = $cond['created_at'];
        }
        if (isset($cond['tagging'])) {
            $where['eq']['b.tagging'] = $cond['tagging'];
        }
        $works = [];
        $ModelOrdersUser = new OrdersUserModel();
        foreach ($ModelOrders->from($ModelOrders->getTable(), 'a')
                     ->leftJoin($ModelOrdersUser->getTable() . ' AS b', 'a.ordersno', '=', 'b.orderno')
                     ->searchWhere($where)
                     ->select(['a.id', 'a.ordersno', 'a.service_user_id'])
                     ->orderBy('a.id', 'ASC')
                     ->cursor() as $row) {
            $works[$row['service_user_id']][] = $row;
        }
        if (empty($works)) {
            return $this->returnMsg(2, '本次任务条件没有对应订单,任务创建失败');
        }
        $insertData = [];
        foreach ($works as $service_user_id => $worksNo) {
            $groups = $inData;
            $groups['service_user_id'] = $service_user_id;
            $groups['shop_id'] = $shop_id;
            $groups['pid'] = 0;
            $groups['nums'] = count($worksNo);
            $groups['orders_condition'] = json_encode($groups['orders_condition']);
            $taskId = $this->model->insertGetId($groups);
            foreach ($worksNo as $k => $row) {
                $callData = [
                    'call_task_id' => $taskId,
                    'ordersno' => $row['ordersno'],
                    'orders_id' => $row['id'],
                    'service_user_id' => $service_user_id,
                    'status' => 0,
//                    'source' => 1,
                    'created_at' => date('Y-m-d H:i:s')
                ];
                $insertData[] = $callData;
            }
        }
        unset($cond, $inData);
        if (empty($insertData)) {
            return $this->returnMsg(2, '任务记录表数据为空,不能记录具体外呼订单');
        }
        $ModelServiceCall = new ServiceCallModel();
        $result = $ModelServiceCall->insert($insertData);
        if ($result) {
            return $this->returnMsg(200, '任务发布成功');
        }
        return $this->returnMsg(2, '任务保存失败');

//        echo $this->getLastSql();

    }

    private function createRecoveryTask($params, $cond)
    {
        if ($params['pid'] <= 0) {
            return $this->returnMsg(2, '请指明原外呼任务');
        }
        $oldTask = $this->model->where(['id' => $params['pid']])->select(['type', 'service_user_id', 'shop_id'])->first();
        $where = [];
        $where['eq']['call_task_id'] = $params['pid'];
//        小旗
        if (isset($cond['tagging'])) {
            $where['eq']['tagging'] = $cond['tagging'];
        }
//        意向标签
        if (!empty($cond['label_id'])) {
            if (is_array($cond['label_id'])) {
                if (count($cond['label_id']) == 1) {
                    $where['eq']['label_id'] = $cond['label_id'][0];
                } else {
                    $where['in']['label_id'] = $cond['label_id'];
                }
            } else {
                $where['eq']['label_id'] = $cond['label_id'];
            }
        }
//        已拨状态
        if (!empty($cond['old_call_status'])) {
            $where['eq']['status'] = $cond['old_call_status'];
        }
//        开始找出符合的原任务
        $ModelServiceCall = new ServiceCallModel();
        $rows = $ModelServiceCall->searchWhere($where)->get();

        if (empty($rows)) {
            return $this->returnMsg(10, '没有回收的订单');
        }
        $nowTaskData = [
            'type' => 0,
            'title' => $params['title'],
            'pid' => $params['pid'],
            'users_id' => $params['user']['id'],
            'service_user_id' => $oldTask['service_user_id'],
            'shop_id' => $oldTask['shop_id'],
            'speech' => $params['speech'] ?? '',
            'orders_condition' => json_encode($cond),
            'status' => 0,
            'nums' => count($rows),
            'weight' => $params['weight'] ?? 0,
        ];
        $taskId = $this->model->insertGetId($nowTaskData);
        if ($taskId <= 0) {
            return $this->returnMsg(10, '创建任务单失败');
        }
        $insertData = [];
        foreach ($rows as $row) {
            $callData = [
                'call_task_id' => $taskId,
                'ordersno' => $row['ordersno'],
                'orders_id' => $row['id'],
                'service_user_id' => $row['service_user_id'],
                'status' => 0,
                'created_at' => date('Y-m-d H:i:s')
            ];
            $insertData[] = $callData;
        }
        $result = $ModelServiceCall->insert($insertData);
        if ($result) {
            return $this->returnMsg(200, '回收任务发布成功');
        }
        return $this->returnMsg(2, '回收任务保存失败');

    }

//    上传数据
    public function import($postData)
    {
        dispatch(new TaskUploadExcel('CallTask', 0, $postData))->onQueue('TaskUploadExcelDispose');
        return $this->returnMsg(200, '上传成功,等待后台分析后更新数据');
    }


}
